package com.zjzywl.smoke.controller;

import com.zjzywl.smoke.authenticate.AuthUser;
import com.zjzywl.smoke.config.AppConfig;
import com.zjzywl.smoke.entity.Building;
import com.zjzywl.smoke.entity.Inform;
import com.zjzywl.smoke.entity.NoticeInfo;
import com.zjzywl.smoke.entity.SysUser;
import com.zjzywl.smoke.util.DisposeAlarm;
import com.zjzywl.smoke.util.RestPageImpl;
import com.zjzywl.smoke.util.RestResult;
import com.zjzywl.smoke.util.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.io.File;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/info")
public class InformationNotificationController extends BaseController {
    @Autowired
    private AppConfig appConfig;

    // 获取公告信息
    @RequestMapping(value = "/getNotice", method = RequestMethod.GET)
    public WebResult getNotice(@RequestParam("beginTime") String beginTime, @RequestParam("endTime") String endTime,HttpServletRequest request) {
        try {
            ResponseEntity<Object> result = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/info/getNotice?beginTime=" + beginTime + "&endTime=" + endTime+ "?" + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(result);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }

    //图片上传
    @PostMapping(value = "/uploadPic")
    public WebResult save(HttpServletRequest request) {
        MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = Murequest.getFileMap();//得到文件map对象
        List<String> notice = null;
        try {
            if (files != null) {
                notice = loadPic(files, "notice");
            }
            return WebResult.OK(notice);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }
    //新增 修改公告
    @PostMapping("/putNotice")
    public WebResult save(@RequestBody()NoticeInfo noticeInfo) {
        try {
            ResponseEntity<NoticeInfo> history = appConfig.restTemplate()
                    .postForEntity(appConfig.getGetDataIp() + "/info/putNotice" , noticeInfo, NoticeInfo.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 获取通知信息
    @GetMapping("/getInform")
    public WebResult getInform(@RequestParam("beginTime") String beginTime, @RequestParam("endTime") String endTime,HttpServletRequest request) {
        try {
            ResponseEntity<Object> result = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/info/getInform?beginTime=" + beginTime + "&endTime=" + endTime+ "?" + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(result);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }

    // 发布通知信息
    @GetMapping("/putInform")
    public WebResult getInform(@RequestParam("content") String content) {
        try {
            ResponseEntity<Object> result = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/info/putInform?content=" + content, Object.class);
            return WebResult.OK(result);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }

    // 删除通知信息
    @DeleteMapping("/delInform")
    public WebResult getInform(@RequestParam("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/info/delInform?id=" + id);
            return WebResult.OK();
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }

    //apk查询公告列表（只查询未失效的公告内容）
    @GetMapping("/getNoticeByHasExpired")
    public WebResult getNoticeByHasExpired() {
        try {
            ResponseEntity<Object> result = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/info/getNoticeByHasExpired", Object.class);
            return WebResult.OK(result);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }

    // 删除通知信息
    @DeleteMapping("/delNotice")
    public WebResult getNotice(@RequestParam("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/info/delNotice?id=" + id);
            return WebResult.OK();
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }


    private List<String> loadPic(Map<String, MultipartFile> files, String code) throws Exception {
        List<String> listUrl = new ArrayList<String>();
        String upaloadUrl = getUploadDir() + code + "/";
        File dir = new File(upaloadUrl);
        if (!dir.exists()) {// 目录不存在则创建
            dir.mkdirs();
        }
        for (MultipartFile file : files.values()) {
            String fileName = getNowDateFormat("yyyyMMddHHmmss") + new Random().nextInt(999999) + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            File tagetFile = new File(upaloadUrl + fileName);// 创建文件对象
            if (!tagetFile.exists()) {// 文件名不存在 则新建文件，并将文件复制到新建文件中
                tagetFile.createNewFile();
                file.transferTo(tagetFile);
                listUrl.add("/upload/" + code + "/" + fileName);
            }
        }
        return listUrl;
    }

    private String getNowDateFormat(String dateFormatType) {
        SimpleDateFormat simformat = new SimpleDateFormat(dateFormatType);
        return simformat.format(new Date());
    }
    //apk查询通知列表（只查询未失效的公告内容）
    @GetMapping("/getApkInform")
    public WebResult getApkInform() {
        try {
            ResponseEntity<Object> result = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/info/getApkInform", Object.class);
            return WebResult.OK(result);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }

}
